<?php
Yii::import('application.components.Reference');
Yii::import('application.components.U');
class PembelianController extends GxController
{
    public function actionCreate()
    {
        if (!Yii::app()->request->isAjaxRequest)
            $this->redirect(url('/'));
        if (isset($_POST) && !empty($_POST)) {
            $msg = 'Faktur pembelian berhasil dibuat.';
            $detils = CJSON::decode($_POST['detil']);
            app()->db->autoCommit = false;
            $transaction = Yii::app()->db->beginTransaction();
            try {
                Yii::import('application.components.Gl');
                $gl = new Gl();
                $beli = new Pembelian;
                $ref = new Reference;
                $docref = $ref->get_next_reference(PEMBELIAN);
                $_POST['Pembelian']['id_bank'] = null;
                foreach ($_POST as $k => $v) {
                    if(is_array($v))
                        continue;
                    if (is_angka($v)) $v = get_number($v);
                    $_POST['Pembelian'][$k] = $v;
                }
                $_POST['Pembelian']['tipe'] = 1;
                $_POST['Pembelian']['no_faktur_beli'] = $docref;
                $_POST['Pembelian']['id_user'] = Yii::app()->user->getId();
                $beli->attributes = $_POST['Pembelian'];
                if (!$beli->save())
                    throw new Exception("Gagal menyimpan faktur pembelian. " . CHtml::errorSummary($beli));
                $ppn = $persedian = 0;
                foreach ($detils as $detil) {
                    $beli_detil = new PembelianDetil;
                    $_POST['PembelianDetil']['barang_id'] = $detil['barang_id'];
                    $_POST['PembelianDetil']['sat'] = $detil['sat'];
                    $_POST['PembelianDetil']['jml'] = get_number($detil['jml']);
                    $_POST['PembelianDetil']['price'] = get_number($detil['price']);
                    $_POST['PembelianDetil']['disc1'] = get_number($detil['disc1']);
                    $_POST['PembelianDetil']['disc2'] = get_number($detil['disc2']);
                    $_POST['PembelianDetil']['pot'] = get_number($detil['pot']);
                    $_POST['PembelianDetil']['totalpot'] = get_number($detil['totalpot']);
                    $_POST['PembelianDetil']['bruto'] = get_number($detil['bruto']);
                    $_POST['PembelianDetil']['nominal'] = get_number($detil['nominal']);
                    $_POST['PembelianDetil']['pcs'] = get_number($detil['pcs']);
                    $_POST['PembelianDetil']['pembelian_id'] = $beli->pembelian_id;
                    $beli_detil->attributes = $_POST['PembelianDetil'];
                    if (!$beli_detil->save())
                        throw new Exception("Gagal menyimpan pembelian detil. " . CHtml::errorSummary($beli_detil));
                    $harga_pcs = $beli_detil->price;
                    if ($beli_detil->barang->ppn) {
                        $ppn += ($beli_detil->nominal) * (10 / 110);
                        $persedian += ($beli_detil->nominal) * (100 / 110);
                        $harga_pcs = ($beli_detil->price) * (100 / 110);
                    }else{
                        $persedian += $beli_detil->nominal;
                    }
                    switch($beli_detil->sat){
                        case 'PCS' :
                            $harga_pcs = $harga_pcs;
                            break;
                        case 'LSN' :
                            $harga_pcs = $harga_pcs / 12;
                            break;
                        case 'PAK' :
                            $harga_pcs = $harga_pcs / $beli_detil->barang->pak_2_pcs;
                            break;
                        default :
                            $harga_pcs = $harga_pcs / $beli_detil->barang->max_2_pcs;
                            break;
                    }
//                    $jml_pcs = $beli_detil->jml * $beli_detil->barang->max_2_pcs;
                    Cogs::count_biaya_beli($beli->tgl, $beli->pembelian_id, $beli_detil->barang_id,
                        $beli_detil->pcs, $harga_pcs);
                    U::add_stock_moves(PEMBELIAN, $beli->pembelian_id, $beli->tgl,
                        $beli_detil->barang_id, GUDANG_PST, $beli_detil->pcs, $beli->no_faktur_beli,
                        $beli_detil->price);
                }
                // persediaan Debet
                $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                    PERSEDIANBARANGDAGANG, '', '', $persedian);
                if ($ppn != 0) {
                    //ppn Debet
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        PPN, '', '', $ppn);
                }
                // biaya bongkar pembelian Debet
                if ($beli->biaya_bongkar != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        BONGKAR, '', '', $beli->biaya_bongkar);
                }
                // biaya angkut pembelian Debet
                if ($beli->biaya_angkut != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        ANGKUT, '', '', $beli->biaya_angkut);
                }
                // utang dagang Kredit
                if ($beli->sisa_tagihan != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        UTANGDAGANG, '', '', -$beli->sisa_tagihan);
                }
                // Kas Kredit
                if ($beli->uang_muka != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        $beli->idBank->account_code, '', '', -$beli->uang_muka);
                }
                // potongan pembelian Kredit
                if ($beli->disc != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        POTONGAN_PEMBELIAN, '', '', -$beli->disc);
                }
                // allowance dagang Kredit
                if ($beli->allowance != 0) {
                    $gl->add_gl(PEMBELIAN, $beli->pembelian_id, $beli->tgl, $beli->no_faktur_beli,
                        ALLOWANCE, '', '', -$beli->allowance);
                }
                $gl->validate();
                $ref->save(PEMBELIAN, $beli->pembelian_id, $docref);
                $transaction->commit();
                $status = true;
            } catch (Exception $ex) {
                $transaction->rollback();
                $status = false;
                $msg = $ex->getMessage();
            }
            echo CJSON::encode(array(
                'success' => $status,
                'id' => $docref,
                'msg' => $msg));
            Yii::app()->end();
        }
    }
    public function actionUpdate($id)
    {
        $model = $this->loadModel($id, 'Pembelian');
        if (isset($_POST) && !empty($_POST)) {
            foreach ($_POST as $k => $v) {
                if (is_angka($v)) $v = get_number($v);
                $_POST['Pembelian'][$k] = $v;
            }
            $msg = "Data gagal disimpan";
            $model->attributes = $_POST['Pembelian'];
            if ($model->save()) {
                $status = true;
                $msg = "Data berhasil di simpan dengan id " . $model->pembelian_id;
            } else {
                $msg .= " " . implode(", ", $model->getErrors());
                $status = false;
            }
            if (Yii::app()->request->isAjaxRequest) {
                echo CJSON::encode(array(
                    'success' => $status,
                    'msg' => $msg
                ));
                Yii::app()->end();
            } else {
                $this->redirect(array('view', 'id' => $model->pembelian_id));
            }
        }
    }
    public function actionDelete($id)
    {
        if (Yii::app()->request->isPostRequest) {
            $msg = 'Data berhasil dihapus.';
            $status = true;
            try {
                $this->loadModel($id, 'Pembelian')->delete();
            } catch (Exception $ex) {
                $status = false;
                $msg = $ex;
            }
            echo CJSON::encode(array(
                'success' => $status,
                'msg' => $msg));
            Yii::app()->end();
        } else
            throw new CHttpException(400,
                Yii::t('app', 'Invalid request. Please do not repeat this request again.'));
    }
    public function actionGetByPO()
    {
        if (!Yii::app()->request->isAjaxRequest) {
            $this->redirect(url('/'));
        }
        $po_id = $_POST['po_id'];
        $pembelian = Pembelian::getByPO($po_id);
        if ($pembelian === false) {
            echo CJSON::encode(array(
                'success' => false,
                'msg' => 'Data tidak ditemukan.'));
            Yii::app()->end();
        } else {
            echo CJSON::encode(array(
                'success' => true,
                'msg' => $pembelian));
            Yii::app()->end();
        }
//        $this->renderJson2($pembelian, $pembelian ? 1 : 0);
    }
    public function actionIndex()
    {
        if (isset($_POST['limit'])) {
            $limit = $_POST['limit'];
        } else {
            $limit = 20;
        }
        if (isset($_POST['start'])) {
            $start = $_POST['start'];
        } else {
            $start = 0;
        }
        $criteria = new CDbCriteria();
        if ((isset ($_POST['mode']) && $_POST['mode'] == 'grid') ||
            (isset($_POST['limit']) && isset($_POST['start']))
        ) {
            $criteria->limit = $limit;
            $criteria->offset = $start;
        }
        $model = Pembelian::model()->findAll($criteria);
        $total = Pembelian::model()->count($criteria);
        $this->renderJson($model, $total);
    }
}